<template>
  <div class="container">
    <el-row :gutter="20">
      <!-- 入库模块 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>车辆入库识别</span>
              <el-tag type="success">支持多车牌识别</el-tag>
            </div>
          </template>

          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleInUpload"
            :disabled="uploading"
          >
            <template #trigger>
              <el-button type="primary" :loading="uploading">
                <el-icon class="el-icon--left"><upload /></el-icon>
                上传入库图片
              </el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">支持格式：JPEG/PNG，最大5MB</div>
            </template>
          </el-upload>

          <div v-if="inResults.length" class="result-container">
            <h4>识别结果（{{ inResults.length }}条）</h4>
            <el-collapse>
              <el-collapse-item
                v-for="(item, index) in inResults"
                :key="index"
                :title="`车牌号：${item.plate_number}`"
              >
                <div class="result-detail">
                  <el-image
                    v-if="item.plate_image"
                    :src="'data:image/jpeg;base64,' + item.plate_image"
                    :preview-src-list="['data:image/jpeg;base64,' + item.plate_image]"
                    fit="cover"
                    class="plate-image"
                  />
                  <div class="detail-info">
                    <el-descriptions :column="1" border>
                      <el-descriptions-item label="置信度">
                        {{ (item.confidence * 100).toFixed(1) }}%
                      </el-descriptions-item>
                      <el-descriptions-item label="入库时间">
                        {{ formatTime(item.entry_time) }}
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-card>
      </el-col>

      <!-- 出库模块 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>车辆出库识别</span>
              <el-tag type="warning">自动计算停车费用</el-tag>
            </div>
          </template>

          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleOutUpload"
            :disabled="uploading"
          >
            <template #trigger>
              <el-button type="warning" :loading="uploading">
                <el-icon class="el-icon--left"><download /></el-icon>
                上传出库图片
              </el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">支持格式：JPEG/PNG，最大5MB</div>
            </template>
          </el-upload>

          <div v-if="outResults.length" class="result-container">
            <h4>结算信息（{{ outResults.length }}条）</h4>
            <el-table :data="outResults" stripe>
              <el-table-column prop="plate_number" label="车牌号" width="120" />
              <el-table-column label="停车时长" width="140">
                <template #default="{row}">
                  <el-tag>{{ row.parking_duration }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="应付金额" width="100">
                <template #default="{row}">
                  <el-text type="danger">{{ row.amount_due }}元</el-text>
                </template>
              </el-table-column>
              <el-table-column label="出库时间">
                <template #default="{row}">
                  {{ formatTime(row.exit_time) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { ElUpload, ElButton } from 'element-plus'
import api from '@/api'
import { formatTime } from '@/utils/format'
import { Upload, Download } from '@element-plus/icons-vue'

const uploading = ref(false)
const inResults = ref([])
const outResults = ref([])

const handleInUpload = async (file) => {
  uploading.value = true
  try {
    const res = await api.vehicleIn(file.raw)
    inResults.value = res.data.success
    handleErrorTips(res.data.errors)
    ElMessage.success(`成功识别${res.data.success.length}个车牌`)
  } catch (error) {
    // 新增错误信息处理
    if (error.response?.data?.errors) {
      handleErrorTips(error.response.data.errors)
    } else {
      ElMessage.error('入库识别失败: ' + (error.message || '未知错误'))
    }
  } finally {
    uploading.value = false
  }
}


const handleOutUpload = async (file) => {
  uploading.value = true
  try {
    const res = await api.vehicleOut(file.raw)
    outResults.value = res.data.success
    handleErrorTips(res.data.errors)
    ElMessage.success(`成功结算${res.data.success.length}个车牌`)
  } catch (error) {
    // 新增错误信息处理
    if (error.response?.data?.errors) {
      handleErrorTips(error.response.data.errors)
    } else {
      ElMessage.error('出库识别失败: ' + (error.message || '未知错误'))
    }
  } finally {
    uploading.value = false
  }
}
const handleErrorTips = (errors) => {
  if (errors?.length) {
    errors.forEach(msg => {
      ElMessage.error({
        message: msg,
        duration: 5000
      })
    })
  }
}
</script>

<style scoped>
.plate-image {
  width: 300px;
  height: 120px;
  border-radius: 4px;
}

.detail-info {
  margin-top: 10px;
  width: 300px;
}

.result-detail {
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>